<?php

namespace yifang\model\relation;

use yifang\model\Relation;
use Closure;
use yifang\utils\Str;
use yifang\db\BaseQuery as Query;
use yifang\model\Model;

abstract class OneToOne extends Relation
{
    /**
     * JOIN类型
     * @var string
     */
    protected $joinType = 'INNER';

    /**
     * 绑定的关联属性
     * @var array
     */
    protected $bindAttr = [];

    /**
     * 关联名
     * @var string
     */
    protected $relation;

    /**
     * 设置join类型
     * @return $this
     */
    public function joinType($type)
    {
        $this->joinType = $type;
        return $this;
    }

    /**
     * 预载入关联查询（JOIN方式）
     * @return void
     */
    public function eagerly(Query $query, $relation, $field = true, $joinType = '', Closure $closure = null, $first = false)
    {
        $name = Str::snake(class_basename($this->parent));
        if ($first) {
            $table = $query->getTable();
            $query->table([$table => $name]);

            if ($query->getOptions('field')) {
                $masterField = $query->getOptions('field');
                $query->removeOption('field');
            } else {
                $masterField = true;
            }
            $query->tableField($masterField, $table, $name);
        }

        // 预载入封装
        $joinTable = $this->query->getTable();
        $joinAlias = $relation;
        $joinType  = $joinType ?: $this->joinType;
        $query->via($joinAlias);
        if ($this instanceof BelongsTo) {
            $foreignKeyExp = $this->foreignKey;
            if (strpos($foreignKeyExp, '.') === false) {
                $foreignKeyExp = $name . '.' . $this->foreignKey;
            }
            $joinOn = $foreignKeyExp . '=' . $joinAlias . '.' . $this->localKey;
        } else {
            $foreignKeyExp = $this->foreignKey;
            if (strpos($foreignKeyExp, '.') === false) {
                $foreignKeyExp = $joinAlias . '.' . $this->foreignKey;
            }
            $joinOn = $name . '.' . $this->localKey . '=' . $foreignKeyExp;
        }
        if ($closure) {
            // 执行闭包查询
            $closure($this->getClosureType($closure));
            // 使用withField指定获取关联的字段
            if ($this->withField) {
                $field = $this->withField;
            }
        }
        $query->join([$joinTable => $joinAlias], $joinOn, $joinType)->tableField($field, $joinTable, $joinAlias, $relation . '__');
    }

    /**
     *  预载入关联查询（数据集）
     * @return mixed
     */
    abstract protected function eagerlySet(array &$resultSet, $relation, array $subRelation = [], Closure $closure = null);

    /**
     * 预载入关联查询（数据）
     * @return mixed
     */
    abstract protected function eagerlyOne(Model $result, $relation, array $subRelation = [], Closure $closure = null);

    /**
     * 预载入关联查询（数据集）
     * @return void
     */
    public function eagerlyResultSet(array &$resultSet, $relation, array $subRelation = [], Closure $closure = null, array $cache = [], $join = false)
    {
        if ($join) {
            // 模型JOIN关联组装
            foreach ($resultSet as $result) {
                $this->match($this->model, $relation, $result);
            }
        } else {
            // IN查询
            $this->eagerlySet($resultSet, $relation, $subRelation, $closure, $cache);
        }
    }

    /**
     * 预载入关联查询（数据）
     * @return void
     */
    public function eagerlyResult(Model $result, $relation, array $subRelation = [], Closure $closure = null, array $cache = [], $join = false)
    {
        if ($join) {
            // 模型JOIN关联组装
            $this->match($this->model, $relation, $result);
        } else {
            // IN查询
            $this->eagerlyOne($result, $relation, $subRelation, $closure, $cache);
        }
    }

    /**
     * 保存（新增）当前关联数据对象
     * @return Model|false
     */
    public function save($data, $replace = true)
    {
        $model = $this->make();
        return $model->replace($replace)->save($data) ? $model : false;
    }

    /**
     * 创建关联对象实例
     * @param array|Model $data
     * @return Model
     */
    public function make($data = [])
    {
        if ($data instanceof Model) {
            $data = $data->getData();
        }
        // 保存关联表数据
        $data[$this->foreignKey] = $this->parent->{$this->localKey};
        return new $this->model($data);
    }

    /**
     * 绑定关联表的属性到父模型属性
     * @return $this
     */
    public function bind(array $attr)
    {
        $this->bindAttr = $attr;
        return $this;
    }

    /**
     * 获取绑定属性
     * @access public
     * @return array
     */
    public function getBindAttr()
    {
        return $this->bindAttr;
    }

    /**
     * 一对一 关联模型预查询拼装
     * @return void
     */
    protected function match($model, $relation, Model $result)
    {
        // 重新组装模型数据
        foreach ($result->getData() as $key => $val) {
            if (strpos($key, '__')) {
                list($name, $attr) = explode('__', $key, 2);
                if ($name == $relation) {
                    $list[$name][$attr] = $val;
                    unset($result->$key);
                }
            }
        }
        if (isset($list[$relation])) {
            $array = array_unique($list[$relation]);
            if (count($array) == 1 && null === current($array)) {
                $relationModel = null;
            } else {
                $relationModel = new $model($list[$relation]);
                $relationModel->setParent(clone $result);
                $relationModel->exists(true);
            }
            if (!empty($this->bindAttr)) {
                $this->bindAttr($result, $relationModel);
            }
        } else {
            $relationModel = null;
        }
        $result->setRelation($relation, $relationModel);
    }

    /**
     * 绑定关联属性到父模型
     */
    protected function bindAttr(Model $result, Model $model = null)
    {
        foreach ($this->bindAttr as $key => $attr) {
            $key   = is_numeric($key) ? $attr : $key;
            $value = $result->getOrigin($key);
            if (!is_null($value)) {
                throw new \Exception('bind attr has exists:' . $key);
            }
            $result->setAttr($key, $model ? $model->$attr : null);
        }
    }

    /**
     * 一对一 关联模型预查询（IN方式）
     * @return array
     */
    protected function eagerlyWhere(array $where, $key, array $subRelation = [], Closure $closure = null, array $cache = [])
    {
        // 预载入关联查询 支持嵌套预载入
        if ($closure) {
            $this->baseQuery = true;
            $closure($this->getClosureType($closure));
        }
        if ($this->withField) {
            $this->query->field($this->withField);
        } elseif ($this->withoutField) {
            $this->query->withoutField($this->withoutField);
        }
        $list = $this->query
            ->where($where)
            ->with($subRelation)
            ->cache($cache[0] ?? false, $cache[1] ?? null, $cache[2] ?? null)
            ->select();
        // 组装模型数据
        $data = [];
        foreach ($list as $set) {
            if (!isset($data[$set->$key])) {
                $data[$set->$key] = $set;
            }
        }
        return $data;
    }
}